package info.johnwheeler.gaestorage.servlet;

import info.johnwheeler.gaestorage.core.Person;
import info.johnwheeler.gaestorage.core.PersonDao;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

public class PersonServlet extends AbstractUploadServlet{
	private PersonDao dao = new PersonDao();
	@Override
	protected void showForm(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ArrayList<Person> people = dao.findAll();
		req.setAttribute("people", people);
		req.getRequestDispatcher("person.jsp").forward(req, resp);
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void handleSubmit(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		ServletFileUpload upload = new ServletFileUpload();
		try {
            FileItemIterator it = upload.getItemIterator(req);

            Person person = new Person();

            while (it.hasNext()) {
                FileItemStream item = it.next();
                String fieldName = item.getFieldName();
                InputStream fieldValue = item.openStream();

                if ("name".equals(fieldName)) {
                    //person.setTitle(Streams.asString(fieldValue));
                	person.setName(Streams.asString(fieldValue));
                    continue;
                }
                if ("cpf".equals(fieldName)) {
                	person.setCpf(Streams.asString(fieldValue));
                    continue;
                }
                if ("mapaddress".equals(fieldName)) {
                	person.setAddress(Streams.asString(fieldValue));
                    continue;
                }
                if ("phone".equals(fieldName)) {
                	person.setPhone(Streams.asString(fieldValue));
                    continue;
                }
            }

            dao.save(person);
            resp.sendRedirect("person?action=display&id=" + person.getId());            
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }     
		
	}

	@Override
	protected void showRecord(long id, HttpServletRequest req,
			HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Person person = dao.findById(id);
        resp.flushBuffer();   
		
	}

}
